/*本文件对axios设置全局默认配置，以及其他配置*/
import axios from 'axios'
import Qs from 'qs'
import store from '../store/index'
import router from '../router/index'
/*-------------------------axios 全局配置----------------------------*/
//axios.defaults.timeout = 1000;
var authToken=""

//定位
global.entryUrl = location.href.split('#')[0];

axios.defaults.headers.common['Authorization'] = authToken
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = "application/json; charset=UTF-8";
axios.defaults.headers.post['Cache-Control'] = "no-cache";
axios.defaults.withCredentials=true//设置cookie,表示跨域请求时是否需要使用凭证


window.baseURL=axios.defaults.baseURL = '/server';
//window.socketUrl = "ws://192.168.0.116:8082/websocket/"
window.socketUrl ="ws://guyun.vicp.io:8085/server/websocket/";


var authToken=localStorage.tokenId || "";
window.message={close(){}}
/*-----------------------axios拦截器---------------*/
//请求拦截器-POST传参序列化
axios.interceptors.request.use((config) => {
	config.headers.Authorization = localStorage.tokenId
	var user=JSON.parse(localStorage.getItem("user"))
	if(config.params && config.method==='get'){
		config.params.userId=user&&user.userId
		config.params.userAgent="web"
	}else if( config.data && config.method==='post'){
		if(Object.prototype.toString.call(config.data)=="[object FormData]"){
			config.data.append('userId',user&&user.userId)
		}else{
			config.data.userId=user&&user.userId
			config.data.userAgent="web"
		}
	}

	return config;
});

//响应拦截器-返回状态判断
axios.interceptors.response.use((response) =>{
	//更新token
  if(response.headers.Authorization){
    localStorage.tokenId=authToken= response.headers.Authorization;
  }

	if(response.data.code && response.data.code==200){
		return response
	}else{
		if(response.data.msg || response.data.message){
			window.message.close()
			window.message=window.rootVue.__proto__.$message({
				type:'error',
				message:response.data.msg  || response.data.message,
				showClose:true,
			})
		}
        return Promise.reject(response);
	}

}, (error) => {//网络无响应时触发
	let httpStatus=error.response.status;
	let msg="";
	let toLogin=false;
	if(httpStatus==401){
		toLogin=true
		msg="登录过期,请重新登录!"
	}else{
		msg=error.response.data.message || error.response.data.msg ||  "网络出错!";
	}
	window.message&& window.message.close()
	window.message=window.rootVue.__proto__.$message({
		type:'error',
		message:msg,
		showClose:true,
	})
	if(toLogin){
		router.replace({
			path: '/login',
		    query: {redirect: router.currentRoute.path}
		})
	}
	return Promise.reject(error);
})


